package net.obxlabs.tweetpad;

import java.awt.event.*;
import net.nexttext.*;
import net.obxlabs.tweetpad.behaviour.*;
import net.obxlabs.tweetpad.stats.*;
import twitter4j.*;

public class Tweet {
	public static final int TEXT_LEFT = 64;
	public static final int TEXT_OFFSET = 28;
	public static final int THUMB_SIZE = 48;
	
	private Sketchpad p;
	private Status status;
	private TextObjectGroup tog;
	private Thumbnail thumbnail;
	
	private float x;
	private float y;
	private float sY;
	
	public Tweet(Sketchpad p, Status status) {
		this.p = p;
		this.status = status;
		thumbnail = new Thumbnail(p, status.getUser().getProfileImageURL().toString(), Counter.LINE_COLORS[Counter.sourceStrToInt(status.getSource())]);

		p.registerMouseEvent(this);
	}
	
	/**
     * Handles a MouseEvent.
     * <p>Registered to be called automatically by the PApplet.</p>
     * 
     * @param event the incoming MouseEvent
     */
	public void mouseEvent(MouseEvent event) {
		// only do something if the first mouse button is clicked
		if ((event.getButton() != MouseEvent.BUTTON1) || 
				(event.getID() != MouseEvent.MOUSE_CLICKED)) {
			return;
		}
		
		// build the TextObject if the click is over the Thumbnail
		int mX = event.getX();
		int mY = event.getY();
		if ((mX > x) && (mX < (x+THUMB_SIZE)) &&
				(mY > y) && (mY < (y+THUMB_SIZE))) {
			buildTextObject();
		}
	}
	
	public void buildTextObject() {
		if (tog == null) {
			p.fill(0, 51, 51);
			p.noStroke();
			tog = p.getBook().addText(status.getText(), TEXT_LEFT, (int)(y+TEXT_OFFSET), 1);
			FollowThumb.link(tog, this);
		}
	}
	
	public void unlinkTextObject() {
		tog = null;
	}
	
	public void initAnim() {
		sY = y;
	}
	
	public void drawThumbnail() {
		try {
			thumbnail.draw(x, y);
		} catch (IllegalArgumentException e) {
			System.out.println("Unable to draw Thumbnail for path "+status.getUser().getProfileImageURL());
		}
	}
	
	public void destroy() {
		// kills the to
		if (tog != null) {
			p.getBook().removeObject(tog);
		}
	}
	
	public String getUpdateTime() { return status.getCreatedAt(); }
	public String getText() { return status.getText(); }
	public int getTextId() { return status.getId(); }
	public String getTextSource() { return status.getSource(); }
	public String getScreenName() { return status.getUser().getScreenName(); }
	public int getUserId() { return status.getUser().getId(); }
	
	public Thumbnail getThumbnail() { return thumbnail; }
	
	public float getSY() { return sY; }
	public float getX() { return x; }
	public float getY() { return y; }
	public void setX(float x) { this.x = x; }
	public void setY(float y) { this.y = y; }
	public void setPosition(float x, float y) {
		setX(x);
		setY(y);
	}
}
